import React, { useRef, useState } from 'react';
import { ActionType, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import { Button, DatePicker, Flex, Image, message, Modal, Select, Tag } from 'antd';
import { deleteUserFun, getPageUserListFun } from '@/services/ant-design-pro/systemApi';
import { PlusOutlined } from '@ant-design/icons';
import UserListModal from '@/pages/system/userList/UserListModal';
import { ButtonEnum } from '@/utils/ButtonEnum';
import { getCapacityList } from '@/utils';
import { getUserFileNumber, updateUserNumberFun } from '@/services/ant-design-pro/panApi';

/*
 * 组件用途: 用户列表
 * 创建日期: 2024/5/14
 * 编写者: XianZhe
 */

const userList = () => {
  // 获取表格方法
  const tableRef = useRef();
  // 状态管理
  const [state, setState] = useState({
    total: 0,
    modalVisit: false,
    selectedUserId: '',
    buttonType: ButtonEnum.ADD,
  });
  const [capacityModal, setCapacityModal] = useState(false);
  const [capacityList, setCapacityList] = useState([]);
  const [capacityValue, setCapacityValue] = useState(null);

  // 修改用户
  const updateRow = (row: any) => {
    setState((prev) => ({
      ...prev,
      modalVisit: true,
      selectedUserId: row.userId,
      buttonType: ButtonEnum.EDIT,
    }));
  };

  // 删除用户
  const removeRow = (row) => {
    // 确认删除用户吗
    Modal.confirm({
      title: '提示',
      content: '确认删除用户吗?',
      onOk() {
        deleteUserFun(row.userId).then((res) => {
          message.success(res.msg);
          tableRef.current?.reload();
        });
      },
    });
  };

  const allocateCapacity = (scope) => {
    console.log(scope);
    setCapacityModal(true);
    setCapacityList(() => {
      return getCapacityList();
    });
    setState((prev) => ({
      ...prev,
      selectedUserId: scope.userId,
    }));
    getUserFileNumber(scope.userId).then((res) => {
      if (res.data) {
        setCapacityValue(res.data.allNumber);
      } else {
        setCapacityValue(null);
      }
    });
  };

  const submitCapacityModal = () => {
    if (!capacityValue) {
      message.error('请选择容量');
      return;
    }
    updateUserNumberFun(state.selectedUserId, capacityValue).then(() => {
      message.success('修改成功');
      setCapacityModal(false);
    });
  };

  const closeCapacityModal = () => {
    setCapacityModal(false);
  };

  const columns: ProColumns<API.RuleListItem>[] = [
    {
      title: '用户ID',
      dataIndex: 'userId',
      key: 'userId',
      search: false,
      copyable: true, // 是否允许复制
    },
    {
      title: '用户名称',
      dataIndex: 'userName',
      key: 'userName',
    },
    {
      title: '用户性别',
      dataIndex: 'sex',
      key: 'sex',
      search: false,
      render: (_, { sex }) => {
        switch (sex) {
          case '0':
            return '男';
          case '1':
            return '女';
          default:
            return '未知';
        }
      },
    },
    {
      title: '手机号',
      dataIndex: 'phonenumber',
      key: 'phonenumber',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      search: false,
    },
    {
      title: '头像',
      dataIndex: 'avatar',
      key: 'avatar',
      search: false,
      width: 70,
      align: 'center',
      render: (_, { avatar }) => {
        return <Image width={40} src={avatar} />;
      },
    },
    {
      title: '所属角色',
      dataIndex: 'role',
      key: 'role',
      search: false,
      render: (_, record) => {
        return (
          <>
            {record.sysRoleList.map((item, index) => {
              return (
                <Tag color={'green'} key={index}>
                  {item.roleName}
                </Tag>
              );
            })}
          </>
        );
      },
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
      key: 'createBy',
      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      // valueType类型可以帮助我们减少渲染
      // 更多配置见：https://procomponents.ant.design/components/schema#valuetype-%E5%88%97%E8%A1%A8
      valueType: 'dateTime',
      renderFormItem: () => {
        return <DatePicker />;
      },
    },
    {
      title: '更新人',
      dataIndex: 'updateBy',
      key: 'updateBy',
      search: false,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '操作',
      key: 'action',
      search: false,
      render: (_, record) => (
        <Flex gap="small">
          <Button type="primary" onClick={() => updateRow(record)}>
            编辑
          </Button>
          <Button onClick={() => removeRow(record)}>删除</Button>
          <Button type={'primary'} onClick={() => allocateCapacity(record)}>
            分配容量
          </Button>
        </Flex>
      ),
    },
  ];

  // 获取表格方法
  const getTableData = async (data) => {
    let res = await getPageUserListFun(data);
    setState((prev) => ({
      ...prev,
      total: res.data.total,
    }));

    // 返回内容必须包含success:true
    // 如果有分页，则必须也返回total
    return {
      success: true,
      data: res.data.records,
      total: res.data.total,
    };
  };

  // 添加用户
  const addUser = () => {
    setState((prev) => ({
      ...prev,
      modalVisit: true,
      selectedUserId: '',
      buttonType: ButtonEnum.ADD,
    }));
  };

  // 弹框关闭时触发
  const closeModal = async (type) => {
    setState((prev) => ({
      ...prev,
      modalVisit: false,
    }));
    if (type) {
      await tableRef.current?.reload();
    }
  };

  return (
    <>
      {/*新建/编辑弹框*/}
      <UserListModal
        modalVisit={state.modalVisit}
        closeModal={closeModal}
        selectedUserId={state.selectedUserId}
        buttonType={state.buttonType}
      />

      {/*列表组件*/}
      <PageContainer header={{ title: '' }}>
        <ProTable
          rowKey={'userId'}
          request={getTableData}
          columns={columns}
          toolBarRender={() => [
            <Button type="primary" key="primary" onClick={addUser}>
              <Flex align={'center'} gap={'small'}>
                <PlusOutlined /> 新增用户
              </Flex>
            </Button>,
          ]}
          search={{
            span: 6,
            labelWidth: 'auto',
            showHiddenNum: true,
            defaultCollapsed: false,
          }}
          actionRef={tableRef}
        />
      </PageContainer>

      {/*分配容量弹框*/}
      <Modal
        open={capacityModal}
        title="分配容量"
        onOk={submitCapacityModal}
        onCancel={closeCapacityModal}
      >
        <Select
          key={'label'}
          value={capacityValue}
          onChange={(value) => setCapacityValue(value)}
          style={{ width: '100%' }}
          options={capacityList}
        />
      </Modal>
    </>
  );
};

export default userList;
